<script setup lang="ts">
defineOptions({
  name: "Complaint"
});

import { ref, onMounted, reactive, computed } from "vue";
import {
  ElButton,
  ElInput,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElTag,
  ElMessage,
  ElMessageBox,
  ElDialog,
  ElSelect,
  ElOption,
  ElForm,
  ElFormItem,
  ElDatePicker,
  ElLoading,
  ElCol,
  ElRow
} from "element-plus";
import {
  getComplaintManagementList,
  getComplaintManagementById,
  addComplaintManagement,
  updateComplaintManagement,
  deleteComplaintManagement
} from "@/api/complaintManagement";
import { findAllCells } from "@/api/cell";
import type {
  ComplaintManagementListVo,
  ComplaintManagementQueryDto,
  UpdateComplaintManagementDto
} from "@/api/complaintManagement";
import type { Cell } from "@/api/cell";

// 搜索关键词
const searchKeyword = ref("");
const contactPhone = ref("");
const selectedCellId = ref("");

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
const loading = ref(false);

// 投诉数据列表
const complaints = ref<ComplaintManagementListVo[]>([]);

// 对话框状态
const dialogVisible = ref(false);
const dialogTitle = ref("录入投诉");
const isEdit = ref(false);

// 小区数据
interface CommunityOption {
  label: string;
  value: string;
}
const communities = ref<CommunityOption[]>([{ label: "全部", value: "" }]);

// 状态选项
const statusOptions = ref([
  { label: "待受理", value: "待受理" },
  { label: "已受理", value: "已受理" }
]);

// 回访状态选项
const revisitStatusOptions = ref([
  { label: "满意", value: "满意" },
  { label: "一般", value: "一般" },
  { label: "不满意", value: "不满意" }
]);

// 表单数据
const formData = reactive<UpdateComplaintManagementDto>({
  id: undefined,
  cellId: "",
  roomNumber: "",
  complainant: "",
  complaintDate: "",
  contactPhone: "",
  status: "待受理",
  complaintContent: "",
  handler: "",
  handlingTime: "",
  revisitPerson: "",
  revisitTime: "",
  revisitContent: "",
  revisitStatus: "",
  processingResult: "",
  attachmentUrl: ""
});

// 表单引用
const formRef = ref();

// 表单校验规则
const rules = {
  cellId: [{ required: true, message: "请选择小区", trigger: "change" }],
  roomNumber: [{ required: true, message: "请输入房号", trigger: "blur" }],
  complainant: [
    { required: true, message: "请输入投诉建议人", trigger: "blur" }
  ],
  complaintDate: [
    { required: true, message: "请选择投诉日期", trigger: "change" }
  ],
  contactPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ],
  complaintContent: [
    { required: true, message: "请输入投诉内容", trigger: "blur" }
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }]
};

// 加载小区数据
const loadCommunities = async () => {
  try {
    const response = await findAllCells();
    if (response.code === 0 || response.code === 200) {
      const cellOptions = response.data.map((cell: Cell) => ({
        label: cell.name,
        value: cell.id.toString()
      }));
      communities.value = [{ label: "全部", value: "" }, ...cellOptions];
    }
  } catch (error) {
    console.error("获取小区数据失败:", error);
  }
};

// 加载投诉数据
const loadComplaintData = async () => {
  loading.value = true;
  const queryDto: ComplaintManagementQueryDto = {
    page: currentPage.value,
    limit: pageSize.value,
    keyword: searchKeyword.value,
    contactPhone: contactPhone.value,
    cellId: selectedCellId.value || undefined
  };

  try {
    const response = await getComplaintManagementList(queryDto);
    if (response.code === 0 || response.code === 200) {
      complaints.value = response.data.list;
      totalCount.value = response.data.total;
    } else {
      ElMessage.error(response.message || "获取投诉数据失败");
    }
  } catch (error) {
    console.error("获取投诉数据失败:", error);
    ElMessage.error("获取投诉数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1;
  loadComplaintData();
};

// 重置搜索
const handleReset = () => {
  searchKeyword.value = "";
  contactPhone.value = "";
  selectedCellId.value = "";
  currentPage.value = 1;
};

// 分页变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadComplaintData();
};

const handlePageChange = (current: number) => {
  currentPage.value = current;
  loadComplaintData();
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(formData, {
    id: undefined,
    cellId: "",
    roomNumber: "",
    complainant: "",
    complaintDate: "",
    contactPhone: "",
    status: "待受理",
    complaintContent: "",
    handler: "",
    handlingTime: "",
    revisitPerson: "",
    revisitTime: "",
    revisitContent: "",
    revisitStatus: "",
    processingResult: "",
    attachmentUrl: ""
  });
};

// 打开添加对话框
const handleAdd = () => {
  isEdit.value = false;
  dialogTitle.value = "录入投诉";
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const handleEdit = async (row: ComplaintManagementListVo) => {
  isEdit.value = true;
  dialogTitle.value = "编辑投诉";
  resetForm();

  try {
    const response = await getComplaintManagementById(row.id!);
    if (response.code === 0 || response.code === 200) {
      const data = response.data;
      Object.assign(formData, {
        id: data.id,
        cellId: data.cellId,
        roomNumber: data.roomNumber,
        complainant: data.complainant,
        complaintDate: data.complaintDate || "",
        contactPhone: data.contactPhone,
        status: data.status,
        complaintContent: data.complaintContent,
        handler: data.handler || "",
        handlingTime: data.handlingTime || "",
        revisitPerson: data.revisitPerson || "",
        revisitTime: data.revisitTime || "",
        revisitContent: data.revisitContent || "",
        revisitStatus: data.revisitStatus || "",
        processingResult: data.processingResult || "",
        attachmentUrl: data.attachmentUrl || ""
      });
      dialogVisible.value = true;
    } else {
      ElMessage.error(response.message || "获取详情失败");
    }
  } catch (error) {
    console.error("获取投诉详情失败:", error);
    ElMessage.error("获取详情失败");
  }
};

// 保存投诉
const handleSave = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    ElLoading.service({
      lock: true,
      text: "正在保存...",
      background: "rgba(0, 0, 0, 0.7)"
    });

    // 格式化所有日期字段为正确的字符串格式
    const formatDateField = (date: any) => {
      if (!date) return "";
      if (typeof date === "string") return date;
      return new Date(date).toISOString().slice(0, 19).replace("T", " ");
    };

    const submitData = {
      ...formData,
      complaintDate: formatDateField(formData.complaintDate),
      handlingTime: formatDateField(formData.handlingTime),
      revisitTime: formatDateField(formData.revisitTime)
    };

    let response;
    if (isEdit.value) {
      response = await updateComplaintManagement(submitData);
    } else {
      response = await addComplaintManagement(submitData);
    }

    if (response.code === 0 || response.code === 200) {
      ElMessage.success(isEdit.value ? "更新成功" : "添加成功");
      dialogVisible.value = false;
      await loadComplaintData();
    } else {
      ElMessage.error(
        response.message || (isEdit.value ? "更新失败" : "添加失败")
      );
    }
  } catch (error: any) {
    console.error("保存投诉失败:", error);
    if (!error?.message?.includes("cancel")) {
      ElMessage.error("保存失败");
    }
  } finally {
    ElLoading.service().close();
  }
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  resetForm();
};

// 删除投诉
const handleDelete = async (row: ComplaintManagementListVo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除投诉记录「${row.complaintContent}」吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const response = await deleteComplaintManagement(row.id!);
    if (response.code === 0 || response.code === 200) {
      ElMessage.success("删除成功");
      await loadComplaintData();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error: any) {
    if (!error?.message?.includes("cancel")) {
      console.error("删除投诉失败:", error);
    }
  }
};

// 处理受理
const handleAccept = async (row: ComplaintManagementListVo) => {
  try {
    await ElMessageBox.prompt("请输入受理人姓名", "确认受理", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /^\S+$/,
      inputErrorMessage: "受理人不能为空"
    }).then(async ({ value }) => {
      const updateData = {
        ...row,
        status: "已受理",
        handler: value,
        // 确保处理时间格式与其他日期字段一致
        handlingTime: new Date().toISOString().slice(0, 19).replace("T", " ")
      };

      const response = await updateComplaintManagement(updateData);
      if (response.code === 0 || response.code === 200) {
        ElMessage.success("受理成功");
        await loadComplaintData();
      } else {
        ElMessage.error(response.message || "受理失败");
      }
    });
  } catch (error: any) {
    if (!error?.message?.includes("cancel")) {
      console.error("受理投诉失败:", error);
    }
  }
};

// 处理回访
const handleRevisit = async (row: ComplaintManagementListVo) => {
  dialogTitle.value = "投诉回访";
  isEdit.value = true;
  resetForm();
  Object.assign(formData, {
    id: row.id,
    cellId: row.cellId,
    roomNumber: row.roomNumber,
    complainant: row.complainant,
    complaintDate: row.complaintDate,
    contactPhone: row.contactPhone,
    status: row.status,
    complaintContent: row.complaintContent,
    handler: row.handler || "",
    handlingTime: row.handlingTime || "",
    revisitPerson: "",
    revisitTime: new Date().toISOString().slice(0, 19).replace("T", " "),
    revisitContent: "",
    revisitStatus: "满意",
    processingResult: row.processingResult || ""
  });
  dialogVisible.value = true;
};

// 格式化日期
const formatDate = (date: string | Date | undefined) => {
  if (!date) return "--";
  const d = new Date(date);
  return d
    .toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit"
    })
    .replace(/\//g, "-");
};

// 状态标签样式
const getStatusTagType = (status: string) => {
  switch (status) {
    case "已受理":
      return "success";
    case "待受理":
      return "warning";
    default:
      return "info";
  }
};

// 回访状态标签样式
const getRevisitStatusTagType = (status: string) => {
  switch (status) {
    case "满意":
      return "success";
    case "一般":
      return "warning";
    case "不满意":
      return "danger";
    default:
      return "info";
  }
};

// 组件挂载时加载数据
onMounted(async () => {
  await loadCommunities();
  await loadComplaintData();
});
</script>

<template>
  <div class="complaint-container">
    <div class="header-bar">
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入姓名/房号/手机号搜索"
          style="width: 300px; margin-right: 10px"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
        <el-button type="primary" @click="handleAdd">+ 录入投诉</el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="complaints"
        style="width: 100%"
        border
      >
        <el-table-column prop="cellName" label="小区" min-width="100" />
        <el-table-column prop="roomNumber" label="房间号" min-width="100" />
        <el-table-column
          prop="complainant"
          label="投诉建议人"
          min-width="100"
        />
        <el-table-column label="投诉日期" min-width="120">
          <template #default="{ row }">
            {{ formatDate(row.complaintDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" min-width="120" />
        <el-table-column prop="status" label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{
              row.status
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="complaintContent"
          label="投诉内容"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column prop="revisitStatus" label="回访状态" min-width="100">
          <template #default="{ row }">
            <el-tag
              v-if="row.revisitStatus"
              :type="getRevisitStatusTagType(row.revisitStatus)"
            >
              {{ row.revisitStatus }}
            </el-tag>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="handler" label="受理人" min-width="100">
          <template #default="{ row }">
            {{ row.handler || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="受理时间" min-width="120">
          <template #default="{ row }">
            {{ formatDate(row.handlingTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === '待受理'"
              type="primary"
              link
              size="small"
              @click="handleAccept(row)"
            >
              受理
            </el-button>
            <el-button
              v-if="row.status === '已受理'"
              type="success"
              link
              size="small"
              @click="handleRevisit(row)"
            >
              回访
            </el-button>
            <el-button type="info" link size="small" @click="handleEdit(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, jumper, sizes, total"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 投诉对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :before-close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="complaint-form"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="小区" prop="cellId">
              <el-select v-model="formData.cellId" placeholder="请选择小区">
                <el-option
                  v-for="item in communities.filter(item => item.value !== '')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间号" prop="roomNumber">
              <el-input
                v-model="formData.roomNumber"
                placeholder="请输入房间号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投诉建议人" prop="complainant">
              <el-input
                v-model="formData.complainant"
                placeholder="请输入投诉建议人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投诉日期" prop="complaintDate">
              <el-date-picker
                v-model="formData.complaintDate"
                type="datetime"
                placeholder="请选择投诉日期"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input
                v-model="formData.contactPhone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="受理人" prop="handler">
              <el-input v-model="formData.handler" placeholder="请输入受理人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="受理时间" prop="handlingTime">
              <el-date-picker
                v-model="formData.handlingTime"
                type="datetime"
                placeholder="请选择受理时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="投诉内容" prop="complaintContent">
              <el-input
                v-model="formData.complaintContent"
                type="textarea"
                :rows="3"
                placeholder="请输入投诉内容"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="回访人" prop="revisitPerson">
              <el-input
                v-model="formData.revisitPerson"
                placeholder="请输入回访人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="回访时间" prop="revisitTime">
              <el-date-picker
                v-model="formData.revisitTime"
                type="datetime"
                placeholder="请选择回访时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="回访状态" prop="revisitStatus">
              <el-select
                v-model="formData.revisitStatus"
                placeholder="请选择回访状态"
              >
                <el-option
                  v-for="item in revisitStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="处理结果" prop="processingResult">
              <el-input
                v-model="formData.processingResult"
                type="textarea"
                :rows="3"
                placeholder="请输入处理结果"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="回访内容" prop="revisitContent">
              <el-input
                v-model="formData.revisitContent"
                type="textarea"
                :rows="3"
                placeholder="请输入回访内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.complaint-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.header-bar {
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.table-container {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.complaint-form {
  max-height: 60vh;
  overflow-y: auto;
}

.dialog-footer {
  text-align: right;
}
</style>
